package com.szy.douyou_gateway.web;


import com.szy.douyou_gateway.config.ResultDTO;
import com.szy.douyou_gateway.config.dto.LoginDto;
import com.szy.douyou_gateway.config.util.JwtUtils;
import com.szy.douyou_gateway.dao.Users;
import com.szy.douyou_gateway.service.UsersService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录接口
 *
 * @author sunziyan
 * @date 2022/02/08
 */
@RestController
public class LoginController {

    @Resource
    private UsersService usersService;

    @Resource
    private JwtUtils jwtUtils;

    /**
     * 用户注册
     *
     * @param user
     * @return
     */
    @PostMapping("/register")
    public ResultDTO Register(@Validated @RequestBody Users user) {

        return usersService.addUser(user);
    }

    /**
     * 登录
     *
     * @param loginDto
     * @param response
     * @return
     */
    @PostMapping("/login")
    public ResultDTO login(@Validated @RequestBody LoginDto loginDto, HttpServletResponse response) {

        ResultDTO<Users> result = usersService.getUserByUserName(loginDto.getUserName(), loginDto.getUserPassword());
        Users user = result.getData();
        //如果用户校验出错返回错误信息
        if (result.getSuccess() == false) {
            return result;
        }

        //通过userId生成jwt并放在header里面
        String jwt = jwtUtils.generateToken(result.getData().getUserId());
        response.setHeader("Authorization", jwt);
        response.setHeader("Access-Control-Expose-Headers", "Authorization");

        user.setUserPassword(null);

        return ResultDTO.success(user);
    }

    /**
     * 登出
     *
     * @return
     */
    @RequiresAuthentication
    @GetMapping("/logout")
    public ResultDTO logout() {
        SecurityUtils.getSubject().logout();
        return ResultDTO.success(null);
    }






}
